import 'dart:async';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:tiktokadult/hj_model/user/user_info_model.dart';
import 'package:tiktokadult/hj_page/mine_business/chat/widget/chat_logic.dart';
import 'package:tiktokadult/hj_utils/api_service/mine_service.dart';
import 'package:tiktokadult/hj_utils/global.dart';
import 'package:tiktokadult/tools_base/debug_log.dart';
import 'package:tiktokadult/tools_base/event_bus/event_bus_util.dart';
import 'package:tiktokadult/tools_base/event_bus/events.dart';
import 'package:tiktokadult/tools_base/global_store/store.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

import '../home_business/search_page/search_result_page/search_video_result_page.dart';

//车牌_CAR_NO  影片 COVER 短片_SP 图集_COVER 动态_POST 商品_StoreGoods

class UserCenterController extends GetxController with GetTickerProviderStateMixin {
  late int id;
  UserInfoModel? model;
  RxBool isShowAppMenu = false.obs;
  double? expandedHeight;
  GlobalKey globalKey = GlobalKey();
  List<String> get titleArr => ['影视', '抖音', '帖子', '图集'];
  List<SearchType> get titleParam => [SearchType.video, SearchType.short, SearchType.post, SearchType.image];
  late TabController mainTabCtr;
  late ScrollController scrollCtr = ScrollController()
    ..addListener(() {
      if (scrollCtr.offset > 190) {
        isShowAppMenu.value = true;
      } else {
        isShowAppMenu.value = false;
      }
    });
  final refreshController = RefreshController();

  late StreamSubscription stream;

  @override
  void onInit() {
    super.onInit();
    id = Get.arguments['uid'];
  }

  @override
  void onReady() {
    super.onReady();
    mainTabCtr = TabController(length: titleArr.length, vsync: this);
    stream = eventBus.on<CollectStatusModel>((event) {
      if (event.uid == id) fetchUserInfo();
    });
    fetchUserInfo();
  }

  @override
  void dispose() {
    super.dispose();
    eventBus.off(stream);
  }

  void calculateHeaderHeight() {
    if (expandedHeight == null) {
      final RenderBox? renderBox = globalKey.currentContext?.findRenderObject() as RenderBox?;
      if (renderBox != null) {
        expandedHeight = renderBox.size.height;
      } else {
        debugLog('无法获取 calculateHeaderHeight');
      }
      WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
        update();
      });
    }
  }

  fetchUserInfo() async {
    if (globalStore.isMe(id)) {
      model = globalStore.meInfo;
      update();
    }
    final result = await MineService.getUserInfo(id);
    model = result;
    update();
  }

  gotoPrivateChat() {
    if (globalStore.isMe(model?.uid)) {
      showToast("不能给自己私信哦～");
      return;
    }

    ChatLogic.goToChatPage(
      uid: model?.uid ?? 0,
      userName: model?.name ?? '',
    );
  }
}
